// pages/coupons/coupons.js
var that,
  api = new (require('../../utils/api.js')),
  headimg = api.getimgurl(),
  app = getApp(),
  util = new (require('../../utils/util.js'));
Page({

  /**
   * 页面的初始数据
   */
  data: {
    selectindex: 1,
    couponslist: [],
    ischeck: !1,
    page: 1,
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: function (options) {
    that = this;
  },
  afterlogin: {
    logininfo: res => {
      that.getdata();
    }
  },
  getdata() {
    let { selectindex, page, couponslist } = that.data
    let { corpInvoiceTag } = app.logininfo
    that.setData({ corpInvoiceTag })
    api.couponlists({ page, cateId: selectindex }, res => {
      if (res.data.code == 0) {
        let { couponArr, nextPage } = res.data.entity.data
        if (couponArr.length > 0) {
          couponArr.forEach(x => {
            x.apart = 0
            if (x.status == 1) {
              let timestamp = Date.parse(new Date()) / 1000
              let apart = Math.ceil((x.endTime - timestamp) / (24 * 60 * 60))
              x.apart = apart
            }
            x.starttime = util.formatDate(new Date(x.startTime * 1000))
            x.endtime = util.formatDate(new Date(x.endTime * 1000))
            x.data = util.formatDate(new Date(x.addTime * 1000))

            if (x.useTime != 0) {
              x.useTime = util.formatDate(new Date(x.useTime * 1000))
            }
            couponslist.push(x)
          })
        }
        that.setData({ couponslist, nextPage })
      }
    })
  },
  toselect(e) {
    let { index } = e.currentTarget.dataset, { selectindex } = that.data;
    if (selectindex == index) {
      return;
    }
    this.setData({ selectindex: index, page: 1, couponslist: [] }, () => {
      that.getdata()
    });
  },
  todetail(e) {
    let { selectindex } = that.data
    if (selectindex == 1) {
      wx.navigateTo({
        url: '../couponDetail/couponDetail?id=' + e.currentTarget.dataset.id,
      })
    } else {
      that.setData({ ischeck: !0 })
    }
  },
  close() {
    that.setData({ ischeck: !1 })
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {

  },

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    that.setData({ couponslist: [], page: 1 }, () => {
      if (app.logininfo) {
        that.getdata()
      } else {
        util.setwatcher(app, this.afterlogin)
      }
    })
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  },

  /**
   * 页面相关事件处理函数--监听用户下拉动作
   */
  onPullDownRefresh: function () {

  },

  /**
   * 页面上拉触底事件的处理函数
   */
  onReachBottom: function () {
    let { nextPage, page } = that.data
    if (nextPage == 1) {
      page = page + 1
      that.setData({ page }, () => {
        that.getdata()
      })
    }
  },

  /**
   * 用户点击右上角分享
   */
  onShareAppMessage: function () {

  }
})